package com.lucy.viewer.controller;

import com.lucy.viewer.event.FileCreatedEvent;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.params.ViewerFileTouchParams;
import com.lucy.viewer.service.ViewerFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("viewer")
@AllArgsConstructor
@Api(tags = "文件管理")
public class ViewerFileController {
    ViewerFileService fileService;

    ApplicationContext context;

    @GetMapping("download/{fileId}")
    @ApiOperation(value = "文件下载",notes = "")
    public ResponseEntity<byte[]> downLoadById(@PathVariable("fileId") String fileId, HttpServletRequest request) throws Exception {

        ViewerFile file = fileService.getViewerFile(fileId);
        return fileService.downloadMethod(fileService.getViewerFileStream(fileId), request,file);
    }

    @PostMapping("file/touch")
    @ApiOperation(value = "文件创建",notes = "")
    public Object fileTouch(@Validated @RequestBody ViewerFileTouchParams params){
        // 获取文件名称
        String fileName = params.getFileName();
        ViewerFile file = fileService.fileTouch(fileName);
        // 执行创建事件 -- 并刷新 viewerFile 值
        file = fileService.createViewerFile(file);
        // 发布文件创建事件
        context.publishEvent(new FileCreatedEvent(this,file));
        // 获取返回 key
        String resKey = file.getKey();
        Map<String,Object> res = new HashMap<>();
        res.put("code",200);
        res.put("success",true);
        res.put("msg","成功");
        res.put("data",resKey);
        return res;
    }

}
